<!DOCTYPE html>
<html>
<head>
  <title>PDF.js Download Example</title>
</head>
<body>
  <button id="download-btn">下载为pdf</button>
  <canvas id="the-canvas"></canvas>
  <script src="./build/pdf.mjs" type="module"></script>
  <script src="./build/pdf.worker.mjs" type="module"></script>
  
  <script type="module">
    import * as pdfjsLib from "./build/pdf.mjs";
    pdfjsLib.GlobalWorkerOptions.workerSrc = "./build/pdf.worker.mjs";
    var url = "https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf";
    
    var pdfDoc = null;
    var pageNum = 1;
    var pageRendering = false;
    var pageNumPending = null;
    var scale = 1.5;
    var canvas = document.getElementById("the-canvas");
    var ctx = canvas.getContext("2d");

    pdfjsLib.getDocument(url).promise.then(function (pdfDoc_) {
      console.log(pdfDoc_);
      pdfDoc = pdfDoc_;
      renderPage(pageNum);
    });

    function renderPage(num) {
      pageRendering = true;
      pdfDoc.getPage(num).then(function (page) {
        var viewport = page.getViewport({ scale: scale });
        canvas.height = document.documentElement.clientHeight;
        canvas.width = document.documentElement.clientWidth;

        var renderContext = {
          canvasContext: ctx,
          viewport: viewport,
        };
        var renderTask = page.render(renderContext);

        renderTask.promise.then(function () {
          pageRendering = false;
          if (pageNumPending !== null) {
            renderPage(pageNumPending);
            pageNumPending = null;
          }
        });
      });
    }

    const download = function () {
      pdfjsLib.getDocument(url).promise.then(function (pdfDoc) {
        console.log(pdfDoc,'sssssss');
        return pdfDoc.getData();
      }).then(function (pdfData) {
        const blob = new Blob([pdfData], { type: 'application/pdf' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'downloaded.pdf';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }).catch(function (error) {
        console.error('Error downloading PDF: ', error);
      });
    };

    document.getElementById('download-btn').addEventListener('click', download);
  </script>
</body>
</html>
